<template>
  <Popup v-model="lvalue" overlay style="height:100vh;" position="top">
    NewForm
    <div>
      <vanForm style="padding:15px;" @submit="saveRecord">
        <template v-for="(item,index) in recordValue">
          <Row type="flex" style="display: flex;align-items: center">
            <Col span="6"> {{ item.string }}</Col>
            <Col span="18">
              <Field :model="model" :id="id" style="padding: 10px;text-align: center;alignment: right"
                     :key="index"
                     :field="item"
                     :value="item"
                     :edit="true"
                     :title="true" :context="context" :saveFast="false"
              />
            </Col>
          </Row>
        </template>
        <div style="margin: 16px;">
          <Button round block type="info" native-type="submit">
            提交
          </Button>
          <Button round block type="warning" @click="$emit('update:value',false)">
            取消
          </Button>
        </div>
      </vanForm>
      {{recordValue}}
    </div>
  </Popup>
</template>

<script>

  import {baseField, modelMethod, msgField, ratingField, record, seoField, websiteField} from '../api/http'
  import gql from 'graphql-tag'
  import {Button, Col, Form, Popup, Row} from "vant"

  export default {
    name: 'NewForm',
    components: {
      vanForm: Form, Row, Col, Popup, Button
    },
    props: {
      model: {type: String, default: ''},
      value: {type: Boolean, default: false}
    },
    data: function () {
      return {
        datas: {},
        jfields: null,
        dataField: null,
        context: {},
        recordValue: [],
        id: null,
        doEdit: false,
        activeNames: [],
        formShow: false,
        result: {},
        queryFields: [],
        otherFields: [],
        website: false,
        seo: false,
        rating: false,
        mail: false, lvalue: this.value
      }
    },
    computed: {
      change() {
        if (this.recordValue) {
          for (let fieldName of this.recordValue) {
            let field = Object.values(fieldName)[0]
            if (field.change) {
              return true
            }
          }
        }
        return false
      },

    },
    watch: {
      value(to, from) {
        this.lvalue = to
      },
      dataField: function (to, from) {
        this.refersh()
      },
      jfields(to, from) {
        this.refersh()
      },
      defaultValue(to, from) {
        this.recordValue = to
        for (let item in to) {
          this.recordValue[item]['cval'] = to[item].value
        }
      }
    },

    mounted: function () {

    },
    apollo: {
      jfields: {
        query: gql`query qdv($model:String){
          jfields:allJfield(model:$model)
          }`,
        variables() {
          return {
            model: this.model
          }
        },
        skip() {
          return !(this.model && this.value)
        }
      },
      dataField: {
        query: gql`query qdv($domain:String){
          dataField:allMobileModel(domain:$domain) {
              fieldsRecIds{
                name
              }
            }
          }`,
        variables() {
          return {
            domain: JSON.stringify([['model', '=', this.model]])
          }
        },
        skip() {
          return !(this.model && this.value)
        }

      },
      defaultValue: {
        query: gql`query qdv($model:String!){
          defaultValue:allDefaultValue(model:$model)
         }`,
        variables() {
          return {
            model: this.model
          }
        },
        skip() {
          return !(this.model && this.value)
        }
      }
    },
    methods: {
      refersh() {
        if (this.dataField && this.jfields && !this.doEdit) {
          let val = []
          let other = []
          let dfields = this.dataField[0] && this.dataField[0].fieldsRecIds ? this.dataField[0].fieldsRecIds.map(x => x.name) : []
          for (let item of Object.keys(this.jfields)) {
            if (websiteField.indexOf(item) >= 0) {
              this.website = true
            } else if (baseField.indexOf(item) >= 0) {
              // this.website = true
            } else if (seoField.indexOf(item) >= 0) {
              this.seo = true
            } else if (ratingField.indexOf(item) >= 0) {
              this.rating = true
            } else if (msgField.indexOf(item) >= 0) {
              this.mail = true
            } else if (dfields.indexOf(item) >= 0 || item === 'id' || item === 'display_name' || item === 'context') {
              val.push(item)
            } else {
              let v = {}
              v[item] = this.jfields[item]
              other.push(v)
            }
          }
          this.queryFields = val
          this.otherFields = other
        }
      },
      switchData(id) {

      },
      toggle(field) {
        field.value = !field.value
      },
      cancel: function () {
        this.$router.back()

      },
      writeDict: function () {
        let v = {}
        for (let field of this.recordValue) {
          if (field.change) {
            v[field.name] = field.newval
          }
        }
        return v
      },
      saveRecord: function (close) {
        let self = this
        let writeDict = this.writeDict(this.recordValue)
        this.$apollo.mutate({
          mutation: gql`mutation($model:String!,$value:JSON!){
  createRecord(model:$model,value:$value){
    ok
  }
}`,
          variables: {model: this.model, value: writeDict}
        })
          .then(function (response) {
            if (response && response.data.createRecord.ok) {
              if (close) {
                self.$router.back()
              }
            } else if (response && !response.data.createRecord.ok) {
              // self.app_root.toast(response.result.errMsg)
            }
          })
          .catch(function (error) {
            console.log(error, __filename)
          })
      },

      saveLayout: function () {
        let self = this
        let fields = this.recordValue.map(x => Object.keys(x)[0])
        modelMethod('mobile.model', 'set_field_name', [this.model, 'record', fields]).then(
          function (reponse) {
            self.doEdit = false
          },
          function (error) {
            console.error(error)
          }
        )
      }
    }
    // beforeRouteEnter (to, from, next) {
    //   const model = to.params.model
    //   if (model) {
    //     next(instance => instance.switchData(model))
    //   } else {
    //     next(new Error('未指定ID'))
    //   }
    // },
    // // 在同一组件对应的多个路由间切换时触发
    // beforeRouteUpdate (to, from, next) {
    //   const model = to.params.model + to.params.id
    //   if (model) {
    //     this.switchData(model)
    //     next()
    //   } else {
    //     next(new Error('未指定ID'))
    //   }
    // }
  }
</script>
